﻿using Orchard;
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Core.Contents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orchard.Themes;

namespace Mod.DisplayTypes.Controllers
{
    [Themed]
    public class DisplayController : Controller
    {
        private readonly IContentManager contentManager;

        public DisplayController(IContentManager contentManager, IShapeFactory shapeFactory, IOrchardServices services)
        {
            this.contentManager = contentManager;
            Shape = shapeFactory;
            Services = services;
            T = NullLocalizer.Instance;
        }

        dynamic Shape { get; set; }
        public IOrchardServices Services { get; private set; }
        public Localizer T { get; set; }

        public ActionResult Item(int id, string displayType)
        {
            
            var actualDisplayType = string.IsNullOrWhiteSpace(displayType) ? "Detail" : displayType;
            actualDisplayType = UppercaseFirst(actualDisplayType);

            var contentItem = contentManager.Get(id, VersionOptions.Published);

            if (contentItem == null)
                return HttpNotFound();

            if (!Services.Authorizer.Authorize(Permissions.ViewContent, contentItem, T("Cannot view content")))
            {
                return new HttpUnauthorizedResult();
            }

            dynamic model = contentManager.BuildDisplay(contentItem, actualDisplayType);
            return View((object)model);
        }

        private static string UppercaseFirst(string s)
        {
            return char.ToUpper(s[0]) + s.Substring(1);
        }
    }
}